package topic

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteTopicLogic {
	return &DeleteTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteTopicLogic) DeleteTopic(req *types.TopicDeleteReq) (resp *types.Empty, err error) {

	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{})

	// 检查话题是否存在
	var existTopic model.CsCommunityTopic
	if err = topicQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&existTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existTopic.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.TopicNotFound)
	}

	// 检查是否有关联的帖子（如果有帖子则不能删除）
	postQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{})
	var postCount int64
	if err = postQuery.Session(&gorm.Session{}).Where("topic_id = ?", req.Id).Count(&postCount).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if postCount > 0 {
		return nil, e.NewGrpcErr(codes.FailedPrecondition, e.TopicHasPosts)
	}

	// 删除话题
	if err = topicQuery.Session(&gorm.Session{}).Where("id = ?", existTopic.ID).Delete(&existTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
